﻿using Microsoft.AspNetCore.Mvc.Rendering;
using PlatformNetCore.Common;
using PlatformNetCore.Common.Helper;
using PlatformNetCore.Entity;
using PlatformNetCore.Entity.Models;
using PlatformNetCore.IRepository;
using PlatformNetCore.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace PlatformNetCore.Service
{
    public class MenuService : IMenuService
    {
        private readonly IMenuRepository menuRepository;
        public MenuService(IMenuRepository _menuRepository)
        {
            menuRepository = _menuRepository;
        }

        #region Menu
        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public LayPager<MenuTree> GetMenuPagedList(int pageIndex, int pageSize, Expression<Func<Menu, bool>> predicate)
        {
            var list = menuRepository.GetPagedList(pageIndex, pageSize, predicate);
            LayPager<MenuTree> pmodel = new LayPager<MenuTree>();
            if (list != null)
            {
                pmodel.count = list.TotalItemCount;
                pmodel.msg = CommonConst.Success;
                pmodel.data = GetMenuList(list.ToList());
            }
            return pmodel;
        }
        /// <summary>
        /// 获取前台菜单
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public List<Menu> GetMenuList(Expression<Func<Menu, bool>> predicate)
        {
            var rightList = CacheHelper.Get<List<Menu>>(CommonConst.CacheMenu);
            if (rightList == null)
            {
                rightList = menuRepository.GetList(predicate).ToList();
                CacheHelper.Set(CommonConst.CacheMenu, rightList, CommonConst.RightListExpire);
            }
            return rightList;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultResponse<Menu> GetMenu(string id)
        {
            ResultResponse<Menu> resultResponse = new ResultResponse<Menu>() { success = false, msg = CommonConst.Fail };
            resultResponse.data = menuRepository.GetById(id);
            if (resultResponse.data != null)
            {
                resultResponse.success = true;
                resultResponse.msg = CommonConst.Success;
            }
            return resultResponse;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        public ResultResponse AddMenu(Menu model)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            if (string.IsNullOrWhiteSpace(model.Title))
            {
                response.msg = "标题不能为空!";
                return response;
            }
            model.ID = IdentityCreator.NextIdentity;
            model.Level = 1;
            if (!string.IsNullOrWhiteSpace(model.ParentID))
            {
                Menu menu = menuRepository.GetById(model.ParentID);
                if (menu != null)
                {
                    model.Level = menu.Level + 1;
                    model.ParentID = menu.ID;
                    model.ParentName = menu.Title;
                }
            }
            model.AddDate = DateTime.Now;
            response.success = menuRepository.Add(model);
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="entity"></param>
        public ResultResponse UpdateMenu(Menu model)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            if (string.IsNullOrWhiteSpace(model.Title))
            {
                response.msg = "标题不能为空!";
                return response;
            }
            var o = menuRepository.GetById(model.ID);
            o.Title = model.Title;
            o.MenuType = model.MenuType;
            o.MenuCode = model.MenuCode;
            o.Link = model.Link;
            o.SEOTitle = model.SEOTitle;
            o.SEOKeyword = model.SEOKeyword;
            o.SEODescription = model.SEODescription;
            o.Remark = model.Remark;
            o.SortNo = model.SortNo;
            o.IsAvailable = model.IsAvailable;
            o.UpdateBy = model.UpdateBy;
            o.UpdateDate = DateTime.Now;

            if (!string.IsNullOrWhiteSpace(model.ParentID))
            {
                Menu menu = menuRepository.GetById(model.ParentID);
                if (menu != null)
                {
                    o.Level = menu.Level + 1;
                    o.ParentID = menu.ID;
                    o.ParentName = menu.Title;
                }
            }
            else
            {
                o.Level = 1;
                o.ParentID = string.Empty;
                o.ParentName = string.Empty;
            }

            response.success = menuRepository.Update(o);
            response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            return response;
        }

        /// <summary>
        /// 推荐，取消推荐 操作
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="dataStatus"></param>
        /// <returns></returns>
        public ResultResponse UpdateMenuState(List<string> ids, string userName, DataStatus dataStatus)
        {
            ResultResponse response = new ResultResponse() { success = false, msg = CommonConst.Fail };
            var products = menuRepository.GetList(s => ids.Contains(s.ID)).ToList();
            if (products != null && products.Count > 0)
            {
                switch (dataStatus)
                {
                    case DataStatus.Deleted:
                        response.success = menuRepository.Delete(products);
                        break;
                }
                response.msg = response.success ? CommonConst.Success : CommonConst.Fail;
            }
            return response;
        }
        private List<MenuTree> GetMenuList(List<Menu> list)
        {
            List<MenuTree> menus = new List<MenuTree>();
            list.Where(s => s.Level == 1).OrderBy(o => o.SortNo).ToList().ForEach(k =>
            {
                MenuTree menuTree = new MenuTree()
                {
                    ID = k.ID,
                    SortNo = k.SortNo,
                    AddBy = k.AddBy,
                    AddDate = k.AddDate,
                    checkeds = 0,
                    IsAvailable = k.IsAvailable,
                    IsDel = k.IsDel,
                    Level = k.Level,
                    Link = k.Link,
                    MenuType = k.MenuType,
                    open = true,
                    ParentID = k.ParentID,
                    ParentName = k.ParentName,
                    Remark = k.Remark,
                    SEODescription = k.SEODescription,
                    SEOKeyword = k.SEOKeyword,
                    SEOTitle = k.SEOTitle,
                    Title = k.Title,
                    MenuCode = k.MenuCode
                };
                menus.Add(menuTree);
                menus.AddRange(ReMenuSelect(list, k.ID));
            });
            return menus;
        }

        private List<MenuTree> ReMenuSelect(List<Menu> all, string parentId)
        {
            List<MenuTree> list = new List<MenuTree>();
            all.Where(a => a.ParentID == parentId).OrderBy(b => b.SortNo).ToList().ForEach(k =>
            {
                list.Add(new MenuTree() {
                    ID = k.ID,
                    SortNo = k.SortNo,
                    AddBy = k.AddBy,
                    AddDate = k.AddDate,
                    checkeds = 0,
                    IsAvailable = k.IsAvailable,
                    IsDel = k.IsDel,
                    Level = k.Level,
                    Link = k.Link,
                    MenuType = k.MenuType,
                    open = true,
                    ParentID = k.ParentID,
                    ParentName = k.ParentName,
                    Remark = k.Remark,
                    SEODescription = k.SEODescription,
                    SEOKeyword = k.SEOKeyword,
                    SEOTitle = k.SEOTitle,
                    Title = k.Title,
                    MenuCode = k.MenuCode
                });
                list.AddRange(ReMenuSelect(all, k.ID));
            });
            return list;
        }

        /// <summary>
        /// 获取当前列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<SelectListItem> GetMenuListDLL(bool isSelect = false, bool isAll = false)
        {
            List<Menu> all = menuRepository.GetList(k => k.IsDel == 0).OrderBy(s => s.SortNo).ToList();
            int minLevel = all.Any() ? all.Min(a => a.Level) : 1;
            List<SelectListItem> list = new List<SelectListItem>();
            all.Where(a => a.Level == minLevel).ToList().ForEach(s =>
            {
                list.Add(new SelectListItem { Text = s.Title + "--" + GetMenuTypeName(s.MenuType), Value = s.ID });
                list.AddRange(RecurrentMenuSelect(all, s.ID));
            });

            if (isSelect)
            {
                list.Insert(0, new SelectListItem() { Value = string.Empty, Text = "--请选择--" });
            }
            if (isAll)
            {
                list.Insert(0, new SelectListItem() { Value = string.Empty, Text = "--全部--" });
            }
            return list;
        }
        private List<SelectListItem> RecurrentMenuSelect(IList<Menu> all, string parentId)
        {
            List<SelectListItem> list = new List<SelectListItem>();
            all.Where(a => a.ParentID == parentId).OrderBy(b => b.SortNo).ToList().ForEach(s =>
            {
                string pstr = string.Empty;
                for (int i = 1; i < s.Level; i++)
                {
                    pstr += "　";
                }
                list.Add(new SelectListItem { Text = pstr + s.Title + "--" + GetMenuTypeName(s.MenuType), Value = s.ID });
                list.AddRange(RecurrentMenuSelect(all, s.ID));
            });
            return list;
        }
        public string GetMenuTypeName(string menuType)
        {
            MenuType type = (MenuType)Enum.Parse(typeof(MenuType), menuType, true);
            return EnumHelper.GetEnumDescription(typeof(MenuType), (int)type);
        }
        #endregion
    }
}
